package keer.httpinterface.http;

import keer.httpinterface.HttpInterfaceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 抽象的{@link HttpRequester}实现类
 * @see HttpRequester
 *
 * @author Keer
 * @since 1.0.0
 */
public abstract class AbstractHttpRequester implements HttpRequester {
    private static final Logger logger = LoggerFactory.getLogger(HttpRequester.class);

    @Override
    public final void configure(HttpProperties properties) throws HttpInterfaceException {
        HttpProperties prop = new HttpProperties(properties);
        try {
            configure0(prop);
            logger.info("Configure http requester:{}", prop);
        } catch (Exception e) {
            logger.error("Configured http requester failure:{}", prop, e);
            throw new HttpInterfaceException("Configure http requester failure.", e);
        }
    }

    @Override
    public final HttpResponse request(HttpRequest request) throws HttpInterfaceException {
        HttpResponse response = null;
        try {
            response = request0(request);
            return response;
        } catch (Exception e) {
            throw new HttpInterfaceException("Http request failure.", e);
        }
    }

    /**
     * 用于配置{@link HttpRequester}的抽象方法
     * @param properties 配置信息
     * @throws Exception
     */
    protected abstract void configure0(HttpProperties properties) throws Exception;

    /**
     * 用于实现http请求的抽象方法
     * @param request 请求信息
     * @return 请求结果
     * @throws Exception 抛出任何请求异常
     */
    protected abstract HttpResponse request0(HttpRequest request) throws Exception;
}
